package com.ktg.mes.md.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktg.common.core.domain.APIResult;
import com.ktg.common.core.domain.Result;
import com.ktg.mes.chanjet.entity.TpItem;
import com.ktg.mes.chanjet.service.TpItemService;
import com.ktg.mes.md.domain.MdStatistics;
import com.ktg.mes.md.service.IMdItemService;
import com.ktg.common.annotation.Log;
import com.ktg.common.constant.UserConstants;
import com.ktg.common.core.controller.BaseController;
import com.ktg.common.core.domain.AjaxResult;
import com.ktg.mes.md.domain.ItemType;
import com.ktg.common.core.page.TableDataInfo;
import com.ktg.common.enums.BusinessType;
import com.ktg.common.utils.StringUtils;
import com.ktg.mes.md.domain.MdItem;
import com.ktg.mes.md.service.IItemTypeService;
import com.ktg.mes.md.service.IMdStatisticsService;
import com.ktg.mes.pro.domain.ProTask;
import com.ktg.mes.pro.domain.ProWorkorder;
import com.ktg.mes.pro.service.IProTaskService;
import com.ktg.mes.rec.domain.RecProcessesExt;
import com.ktg.mes.wm.domain.WmStockWillOut;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/mes/md/mditem")
public class MdItemController extends BaseController {

    @Autowired
    private IMdItemService mdItemService;


    @Autowired
    TpItemService tpItemService;

    @Autowired
    private IItemTypeService iItemTypeService;

    @Autowired
    private IProTaskService proTaskService;

    @Autowired
    private IMdStatisticsService mdStatisticsService;


    /**
     * 列表查询
     * @param mdItem
     * @return
     */
    @PreAuthorize("@ss.hasPermi('mes:md:mditem:list')")
    @GetMapping("/list")
    public TableDataInfo list(MdItem mdItem){
        startPage();
//        List<MdItem> list = mdItemService.selectMdItemList(mdItem);
        List<MdItem> list = mdItemService.selectMdItemList2(mdItem);
        return getDataTable(list);
    }

//    @PreAuthorize("@ss.hasPermi('mes:md:mditem:list')")
//    @GetMapping("/list2")
//    public TableDataInfo list2(){
//        startPage();
//    }

    /**
     * 修改生产工单
     */
    @PreAuthorize("@ss.hasPermi('mes:md:mditem:list')")
    @Log(title = "生产工单", businessType = BusinessType.UPDATE)
    @GetMapping("/getStaticticalNameList")
    public AjaxResult getStaticticalNameList(MdItem mdItem,@RequestParam(name="pageNum", defaultValue="1") Integer pageNum,
                                             @RequestParam(name="pageSize", defaultValue="10") Integer pageSize){
        String aa = mdItem.getProcessProductName();
        mdItem.setProcessProductName(null);
        QueryWrapper<MdItem> queryWrapper = new QueryWrapper<>(mdItem);
        queryWrapper.in("process_product_name", Arrays.stream(aa.split(",")).toArray());
        Page<MdItem> page = new Page<MdItem>(pageNum, pageSize);
        IPage<MdItem> pageList = mdItemService.page(page,queryWrapper);
        return AjaxResult.success(pageList);
    }

    /**
     * T+关联
     * @param tpItem
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/getStaticticalNameList2")
    public AjaxResult getStaticticalNameListWithTP(TpItem tpItem, @RequestParam(name="pageNum", defaultValue="1") Integer pageNum,
                                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize){
        String aa = tpItem.getProcessProductName();
        tpItem.setProcessProductName(null);
        QueryWrapper<TpItem> queryWrapper = new QueryWrapper<>(tpItem);
        queryWrapper.in("process_product_name", Arrays.stream(aa.split(",")).toArray());
        Page<TpItem> page = new Page<TpItem>(pageNum, pageSize);
        IPage<TpItem> pageList = tpItemService.page(page,queryWrapper);
        return AjaxResult.success(pageList);
    }

    /**
     * 根据分类名称，分组列表查询
     * @param mdItem
     * @return
     */
    @PreAuthorize("@ss.hasPermi('mes:md:mditem:list')")
    @GetMapping("/processProductName")
    public Result<IPage<RecProcessesExt>> processProductName(MdItem mdItem
            ,@RequestParam(name="pageNum", defaultValue="1") Integer pageNo
            ,@RequestParam(name="pageSize", defaultValue="10") Integer pageSize
            ,HttpServletRequest req){
        APIResult apiLog = new APIResult("查询工序项列表",req,null);
        try {
            QueryWrapper<MdItem> queryWrapper = new QueryWrapper<>();
            queryWrapper.isNotNull("process_product_name");
            queryWrapper.groupBy("process_product_name");
            Page<MdItem> page = new Page<>(pageNo,pageSize);
            IPage<MdItem> pageList = mdItemService.page(page,queryWrapper);
            return apiLog.ok(pageList);
        }catch (Exception e){
            e.printStackTrace();
            return apiLog.error(e);
        }
    }

    /**
     * 打印产品标签
     */
    @GetMapping("/jimureport/{itemId}/{taskId}")
    public JSONObject printData(@PathVariable("itemId") Long itemId,@PathVariable("taskId") String taskId){
        JSONObject jsonObject = new JSONObject();
        MdItem mdItem = mdItemService.selectMdItemById(itemId);
        ArrayList<Object> list = new ArrayList<>();

        //查询产品生产时间
        ProTask task = proTaskService.selectProTaskByTaskId(Long.valueOf(taskId));
        mdItem.setEndTime(task.getProductionDate());
        if(ObjectUtils.isNotEmpty(mdItem.getValidTerm())){
            Calendar instance = Calendar.getInstance();
            instance.setTime(mdItem.getEndTime()); //设置时间
            instance.add(Calendar.MONTH,mdItem.getValidTerm()); // 添加时间，月份，
            mdItem.setValidTime(instance.getTime());
            // Date time = instance.getTime();
        }
        // 批号
        mdItem.setBatchNo(task.getBatchNo());
        list.add(mdItem);
        jsonObject.put("data",list);
        return jsonObject;
    }

    /**
     * 主键查询
     * @param itemId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('mes:md:mditem:query')")
    @GetMapping(value = "/{itemId}")
    public AjaxResult getInfo(@PathVariable Long itemId){
        return AjaxResult.success(mdItemService.selectMdItemById(itemId));
    }

    /**
     * 新增
     * @param mdItem
     * @return
     */
    @PreAuthorize("@ss.hasPermi('mes:md:mditem:add')")
    @Log(title = "物料管理",businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody MdItem mdItem){
        if(UserConstants.NOT_UNIQUE.equals(mdItemService.checkItemCodeUnique(mdItem))){
            return AjaxResult.error("新增物料"+mdItem.getItemCode()+"失败，物料编码已存在");
        }
        if(UserConstants.NOT_UNIQUE.equals(mdItemService.checkItemNameUnique(mdItem))){
            return AjaxResult.error("新增物料"+mdItem.getItemCode()+"失败，物料名称已存在");
        }

        ItemType type =iItemTypeService.selectItemTypeById(mdItem.getItemTypeId());
        if(StringUtils.isNotNull(type)){
            mdItem.setItemTypeCode(type.getItemTypeCode());
            mdItem.setItemTypeName(type.getItemTypeName());
            mdItem.setItemOrProduct(type.getItemOrProduct());
        }
        MdStatistics statistics = mdStatisticsService.getById(mdItem.getProcessProductId());
        if (StringUtils.isNotNull(statistics)){
            mdItem.setProcessProductName(statistics.getStatisticsName());
        }

        mdItem.setCreateBy(getUsername());
        mdItem.setCreateTime(new Date());
        mdItemService.save(mdItem);
        return AjaxResult.success(mdItem);
    }

    /**
     * 更新
     * @param mdItem
     * @return
     */
    @PreAuthorize("@ss.hasPermi('mes:md:mditem:edit')")
    @Log(title = "物料管理",businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody MdItem mdItem){
        if(UserConstants.NOT_UNIQUE.equals(mdItemService.checkItemCodeUnique(mdItem))){
            return AjaxResult.error("新增物料"+mdItem.getItemCode()+"失败，物料编码已存在");
        }
        if(UserConstants.NOT_UNIQUE.equals(mdItemService.checkItemNameUnique(mdItem))){
            return AjaxResult.error("新增物料"+mdItem.getItemCode()+"失败，物料名称已存在");
        }
        ItemType type =iItemTypeService.selectItemTypeById(mdItem.getItemTypeId());
        if(StringUtils.isNotNull(type)){
            mdItem.setItemTypeCode(type.getItemTypeCode());
            mdItem.setItemTypeName(type.getItemTypeName());
            mdItem.setItemOrProduct(type.getItemOrProduct());
        }

        if (mdItem.getProcessProductId() != null){
            MdStatistics mdStatistics = mdStatisticsService.getById(mdItem.getProcessProductId());
            if (mdStatistics != null){
                mdItem.setProcessProductName(mdStatistics.getStatisticsName());
            }
        }

        MdStatistics statistics = mdStatisticsService.getById(mdItem.getProcessProductId());
        if (StringUtils.isNotNull(statistics)){
            mdItem.setProcessProductName(statistics.getStatisticsName());
        }

        if(StringUtils.isNotNull(mdItem.getSafeStockFlag())&& "N".equals(mdItem.getSafeStockFlag())){
            mdItem.setMinStock(0D);
            mdItem.setMaxStock(0D);
        }

        mdItem.setUpdateBy(getUsername());
        mdItem.setUpdateTime(new Date());
        mdItemService.updateById(mdItem);

        return AjaxResult.success(mdItem);
    }

    @PreAuthorize("@ss.hasPermi('mes:md:mditem:remove')")
    @Log(title = "物料管理",businessType = BusinessType.DELETE)
    @DeleteMapping("/{itemIds}")
    public AjaxResult remove(@PathVariable Long[] itemIds){
        return toAjax(mdItemService.deleteByItemIds(itemIds));
    }


    @GetMapping("/stockList")
    public TableDataInfo stockList(MdItem mdItem){
        startPage();
        List<MdItem> list = mdItemService.selectMdItemStockList(mdItem);
        return getDataTable(list);
    }
}
